<template>
  <div class="account-root">
    <div class="account-root-item">
      <div class="account-root-item-box">
        <n-card :bordered="false" content-style="padding:20px 24px !important;">
          <a class="account-root-item-box-theme" :title="appStore.theme == 'dark' ? '浅色' : '深色'"
             @click="changeTheme">
            <n-icon :size="20">
              <Moon v-if="appStore.theme == 'light'"/>
              <WbSunnyFilled v-else/>
            </n-icon>
          </a>
          <div class="account-root-item-box-logo-title">
            <div class="account-root-item-box-logo">
              <img :src="appStore.logo?appStore.logo:logo" alt="">
            </div>
          </div>
          <h1 class="account-root-item-box-title">{{appStore.title}}</h1>
          <div class="account-root-item-box-form-box">
            <n-form ref="loginFormRef"
                    :model="loginForm"
                    :rules="loginFormRules"
                    size="large"
                    :show-label="false"
                    @keydown.enter.prevent="handelLogin">
              <n-form-item path="username">
                <n-input v-model:value="loginForm.username" style="height: 42px;line-height: 42px"
                         placeholder="登录账号"
                         clearable>
                  <template #prefix>
                    <n-icon :size="20" :depth="1">
                      <User/>
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="password">
                <n-input v-model:value="loginForm.password" style="height: 42px;line-height: 42px"
                         type="password"
                         placeholder="登录密码"
                         clearable>
                  <template #prefix>
                    <n-icon :size="20" :depth="1">
                      <Locked/>
                    </n-icon>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item path="verification_code">
                <n-input v-model:value="loginForm.verification_code" style="height: 42px;line-height: 42px"
                         type="text"
                         placeholder="验证码"
                         clearable>
                  <template #prefix>
                    <template v-if="loginForm.captcha">
                      <div style="width: 174px;height: 42px;position: relative;left: -14px">
                        <img style="cursor:pointer;height: 41px;" :src="loginForm.captcha" @click="refreshCaptcha">
                      </div>
                    </template>
                    <template v-else>
                      <n-icon :size="20" :depth="1">
                        <DomainVerificationOutlined/>
                      </n-icon>
                    </template>
                  </template>
                  <template #suffix>
                  </template>
                </n-input>
              </n-form-item>
              <n-form-item :show-feedback="false">
                <div style="display: flex;justify-content: space-between;width: 100%;">
                  <n-checkbox v-model:checked="loginForm.remember">
                    记住我
                  </n-checkbox>
                  <!--                <n-button text  type="tertiary" @click="forgotPassword">忘记密码?</n-button>-->
                </div>
              </n-form-item>
              <n-form-item>
                <n-button type="primary" size="large" block :loading="LoadingLoginBtn" style="height: 42px;line-height: 42px"
                          @click="handelLogin">
                  登录
                </n-button>
              </n-form-item>
            </n-form>
          </div>
        </n-card>
      </div>
    </div>
    <div class="account-root-footer">
      <p style="position: absolute;bottom: 0 !important;width: 100%;">
        {{ appStore.copyright }}
        <br/>
        <a :href="appStore.icp_url" target="_blank" style="text-decoration:none">
          {{ appStore.icp }}
        </a>
        <br/>
        {{ Copyright.system_requirements }}
      </p>
    </div>
  </div>

</template>

<script lang="ts" setup>
import {ref, computed, onBeforeMount} from "vue";
import {useMessage} from "naive-ui"
import {Moon} from "@vicons/ionicons5";
import {WbSunnyFilled,DomainVerificationOutlined} from "@vicons/material";
import {User, Locked} from "@vicons/carbon";
import {UseAppStore} from "@/stores/app.ts";
import {UseUserStore} from "@/stores/user.ts"
import {useRoute, useRouter} from "vue-router";
import {Copyright} from "@/config"
import {ResultEnum} from "@/util/http/enums/httpEnum.ts";
import {Config} from "@/config";
import {Base64} from "js-Base64";
import {getRequest} from '@/api/data.ts'
const LOGIN_NAME = Config.BASE_LOGIN_NAME;
import logo from '@/assets/vite.svg'


const message = useMessage();
const appStore = UseAppStore();
const userStore = UseUserStore();
const router = useRouter();
const route = useRoute();


const loginFormRef = ref(); //登录表单ref
const loginForm = ref({
  username: "",
  password: "",
  verification_code:'',
  captcha:'',
  captcha_key:null,
  remember: false,
});

const loginFormRules = computed(() => {
  return {
    username: {
      required: true,
      trigger: ["blur", "input"],
      message: "请输入登录账号",
    },
    password: {
      required: true,
      trigger: ["blur", "input"],
      validator: (_rule: any, value: string | any[]) => {
        return new Promise<void>((resolve, reject) => {
          if (!value || value === " ") {
            reject(Error("请输入登录密码")); // reject with error message
          } else if (value && value.length < 6) {
            reject(Error("请输入6位或6位以上的登录密码")); // reject with error message
          } else {
            resolve();
          }
        });
      },
    },
    verification_code: {
      required: true,
      trigger: ["blur", "input"],
      message: "请输入验证码",
    },
  };
});
const LoadingLoginBtn = ref(false);

const changeTheme = () => {
  appStore.setTheme(appStore.theme == "dark" ? "light" : "dark");
}


const handelLogin = (e: any) => {
  e.preventDefault();
  loginFormRef.value.validate(async (errors: any) => {
    if (!errors) {
      // message.loading('登录中...');
      LoadingLoginBtn.value = true;
      try {
        const login_data = {username: loginForm.value.username, password: loginForm.value.password,captcha_code:loginForm.value.verification_code,captcha_key:loginForm.value.captcha_key};
        const response=await userStore.login(login_data);
        if (response!=undefined){
          const {code, message: msg} = response;
          message.destroyAll();
          if (code == ResultEnum.SUCCESS) {
            remPws();
            const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
            message.success('登录成功，即将进入系统', {
              duration: 1500,
              onLeave() {
                if (route.name === LOGIN_NAME) {
                  router.replace({name:Config.Home_Name});
                } else router.replace(toPath);
              }
            });
          } else {
            message.error(msg || '登录失败');
          }
        }
      } finally {
        LoadingLoginBtn.value = false;
      }
    }
  })
}
// 记住密码
const remPws = () => {
  if (loginForm.value.remember) {
    let password = Base64.encode(loginForm.value.password); // base64加密
    localStorage.setItem("userName", loginForm.value.username);
    localStorage.setItem("password", password);
  } else {
    localStorage.removeItem("userName");
    localStorage.removeItem("password");
  }
};
// 获取本地储存的密码
const getPwd = () => {
  let username = localStorage.getItem("userName");
  if (username) {
    const pass = localStorage.getItem("password");
    loginForm.value.username = username;
    if (pass != null) {
      loginForm.value.password = Base64.decode(pass);
    } // base64解密
    loginForm.value.remember = true;
  }
};
onBeforeMount(() => {
  getPwd();
  getCaptcha();
})
//忘记密码
// const forgotPassword = () => {
//     message.warning("忘记密码功能暂未实现")
// }
//刷新验证码
const refreshCaptcha=()=>{
  loginForm.value.verification_code='';
  getCaptcha();
}
const getCaptcha=async ()=>{
  await getRequest('captcha').then((res:ResponseResult)=>{
    const {code}=res;
    if (code===200){
      loginForm.value.captcha=res.data.img;
      loginForm.value.captcha_key=res.data.key;
    }else {
      message.error(res.message || '服务器链接失败、请和管理员联系！');
    }
  })
}
</script>

<style scoped lang="scss">
@import "index";
.login-items{
  font-size: 16px !important;
}
</style>